package com.common.common;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;

import com.common.common.utils.AppToast;

import java.util.LinkedList;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements IBaseView {

    private static LinkedList<Activity> mActivityList = new LinkedList<>();
    private Unbinder unbinder;

    protected T mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(setScreenOrientation());
        super.onCreate(savedInstanceState);
        mPresenter = createPresenter();
        addActivity(this);
        Bundle extras = getIntent().getExtras();
        if (savedInstanceState == null) {
            if (extras == null) {
                extras = new Bundle();
            }
        } else {
            if (extras == null) {
                extras = new Bundle(savedInstanceState);
            } else {
                extras.putAll(savedInstanceState);
            }
        }

        initParams(extras);
        setContentView(bindLayout());
        unbinder = ButterKnife.bind(this);
        initView(savedInstanceState);
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeActivity(this);
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    /**
     * @return 返回值为ActivityInfo类型定义的int类型，表示屏幕方向
     * 默认竖直方向
     */
    protected int setScreenOrientation() {
        return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }

    protected abstract T createPresenter();

    //初始化参数
    protected abstract void initParams(Bundle bundle);

    //绑定布局文件id
    protected abstract int bindLayout();

    //初始化控件视图
    protected abstract void initView(Bundle savedInstanceState);

    //初始化数据
    protected abstract void initData();

    protected void addActivity(Activity activity) {
        mActivityList.add(activity);
    }

    protected void removeActivity(Activity activity) {
        mActivityList.remove(activity);
    }

    @Nullable
    protected Activity getTopActivity() {
        if (mActivityList == null || mActivityList.size() == 0) {
            return null;
        }
        return mActivityList.get(0);
    }

    @Override
    public void showToast(String msg) {
        AppToast.showToast(this, msg);
    }

    @Override
    public void showToast(String msg, int timeMillis) {
        AppToast.showToast(this, msg, timeMillis);
    }
}
